<?php
/**
 * 门店数据处理Lib类
 *
 * @access public
 * @author wangbiao<wangbiao@shopex.cn>
 * @version $Id: import.php 2016-07-26 15:00
 */
class o2o_store
{
    /**
     * create_store 门店创建
     * 
     * @param $sdf
     * @return sdf
     */
    function create_store($sdf, &$errmsg)
    {
        $storeObj         = app::get('o2o')->model('store');
        $organizationObj  = app::get('organization')->model('organization');
        $serverObj        = app::get('o2o')->model('server');
        $regionObj        = app::get('o2o')->model('store_regions');
        
        $smsLib        = kernel::single('taoexlib_request_sms');
        $channelLib    = kernel::single('channel_interface_channel');
        $branchLib     = kernel::single('ome_interface_branch');
        $shopLib       = kernel::single('ome_interface_shop');
        $regionLib     = kernel::single('o2o_store_regions');
        
        //开启事务
        $storeObj->db->exec('begin');
        
        //企业组织(注意：批量导入时必须填写所属组织)
        $org_sdf        = array(
                            'org_no' => $sdf['org_no'],
                            'org_name'=> $sdf['org_name'],
                            'org_type' => $sdf['org_type'],
                            'status' => $sdf['status'],
                            'area' => $sdf['area'],
                            'org_level_num' => $sdf['org_level_num'],
                            'org_parents_structure' => $sdf['org_parents_structure'],
                            'parent_id' => $sdf['parent_id'],
                         );
        $is_save    = $organizationObj->save($org_sdf);
        if(!$is_save)
        {
            #事务回滚
            $storeObj->db->rollBack();
            
            $errmsg    .= '保存企业组织出错,组织编码:'. $org_sdf['org_no'] .'。';
            
            return false;
        }
        
        //发送短信签名注册
        if (defined('APP_TOKEN') && defined('APP_SOURCE')) {
            base_kvstore::instance('taoexlib')->fetch('account', $account);
            if (unserialize($account)) {
                $sms_sign = '【'.$org_sdf['org_name'].'】';
                $smsLib->newoauth_request(array('sms_sign'=>$sms_sign));
            }
        }
        
        //如果设定了门店服务端类型获取对应的虚拟仓储类型
        $now_wms_id    = 0;
        if($sdf['server_id']){
            $serverInfo = $serverObj->dump(array('server_id'=>$sdf['server_id']),'type');
            if($serverInfo['type']){
                $wms_type = $channelLib->dump(array('channel_type'=>'wms','node_type'=>$serverInfo['type']),'channel_id');
                $now_wms_id = $wms_type['channel_id'];
            }
        }
        
        //门店
        $store_sdf    = array(
                            'store_bn' => $sdf['org_no'],
                            'name' => $sdf['org_name'],
                            'server_id' => $sdf['server_id'],
                            'addr' => $sdf['addr'],
                            'longitude' => $sdf['longitude'],
                            'latitude' => $sdf['latitude'],
                            'area' => $sdf['area'],
                            'zip' => $sdf['zip'],
                            'contacter' => $sdf['contacter'],
                            'mobile' => $sdf['mobile'],
                            'tel' => $sdf['tel'],
                            'store_type' => $sdf['store_type'],
                            'self_pick' => $sdf['self_pick'],
                            'distribution' => $sdf['distribution'],
                            'aftersales' => $sdf['aftersales'],
                            'confirm' => $sdf['confirm'],
                            'status' => $sdf['status'],
                        );
        $is_save    = $storeObj->save($store_sdf);
        if(!$is_save)
        {
            #事务回滚
            $storeObj->db->rollBack();
            
            $errmsg    .= '保存门店信息出错,门店编码:'. $store_sdf['store_bn'] .'。';
            
            return false;
        }
        
        //生成对应的虚拟仓
        $new_branch = array(
                'branch_bn' => $sdf['org_no'],
                'name' => $sdf['org_name'],
                'storage_code' => $sdf['org_no'],
                'b_type' => 2,
                'b_status' => $sdf['status'],
                'wms_id' => $now_wms_id,
        );
        $save_branch    = $branchLib->save($new_branch);
        if(!$save_branch)
        {
            #事务回滚
            $storeObj->db->rollBack();
            
            $errmsg    .= '门店关联虚拟仓保存失败,门店编码:'. $store_sdf['store_bn'] .'。';
            
            return false;
        }
        
        //生成对应的虚拟店铺
        $new_shop = array(
                'shop_bn' => $sdf['org_no'],
                'name' => $sdf['org_name'],
                's_type' => 2,
                's_status' => $sdf['status'],
        );
        $save_shop    = $shopLib->save($new_shop);
        if(!$save_shop)
        {
            #事务回滚
            $storeObj->db->rollBack();
            
            $errmsg    .= '门店关联线下店铺保存失败,门店编码:'. $store_sdf['store_bn'] .'。';
            
            return false;
        }
        
        //更新相关的仓库和店铺
        $update_data    = array('branch_id'=>$new_branch['branch_id'], 'shop_id'=>$new_shop['shop_id']);
        $update_store   = $storeObj->update($update_data, array('store_id'=>$store_sdf['store_id']));
        if(!$update_store)
        {
            #事务回滚
            $storeObj->db->rollBack();
            
            $errmsg    .= '门店关联仓库、店铺信息更新失败,门店编码:'. $store_sdf['store_bn'] .'。';
            
            return false;
        }
        
        #新增门店关联地区数据信息
        list($temp_package, $temp_region_name, $region_id)    = explode(':', $sdf['area']);
        $region_data    = $regionLib->getRegionById($region_id);
        
        $save_data = array(
                        'store_id' => $store_sdf['store_id'],
                        'region_1' => intval($region_data[1]),
                        'region_2' => intval($region_data[2]),
                        'region_3' => intval($region_data[3]),
                        'region_4' => intval($region_data[4]),
                        'region_5' => intval($region_data[5]),
                    );
        $save_region    = $regionObj->save($save_data);
        if(!$save_region)
        {
            #事务回滚
            $storeObj->db->rollBack();
            
            $errmsg    .= '门店关联地区信息保存失败,门店编码:'. $store_sdf['store_bn'] .'。';
            
            return false;
        }
        
        //如果最新保存的信息有父节点，更新父节点为有下级仓库或门店节点信息
        if($sdf['parent_id'] > 0)
        {
            $p_org_info    = $organizationObj->dump(array('org_id'=>$sdf['parent_id']), 'haschild');
            
            $child_arr     = $organizationObj->getList('org_id', array('parent_id'=>$sdf['parent_id'], 'org_type'=>2), 0, -1);
            
            if(count($child_arr) > 0){
                $org_save_parent_data['haschild'] = $p_org_info['haschild'] | 2;
            }else{
                $org_save_parent_data['haschild'] = $p_org_info['haschild'] ^ 2;
            }
            
            $organizationObj->update($org_save_parent_data, array('org_id'=>$sdf['parent_id']));
        }
        
        //事务确认
        $storeObj->db->commit();
        
        return true;
    }
    
    /**
     * 门店数据有效性检查Lib类
     * @param unknown $params
     * @param unknown $err_msg
     * @return Array
     */
    public function checkAddParams(&$params, &$err_msg)
    {
        $organizationObj    = app::get('organization')->model('organization');
        
        //拆分组织经纬度信息
        if(isset($params['coordinate']))
        {
            $coordinate = explode(',',$params['coordinate']);
            $params['longitude'] = $coordinate[0];
            $params['latitude'] =  $coordinate[1];
            
            if(empty($params['longitude']) || empty($params['latitude']))
            {
                $err_msg    = '门店经纬度填写错误';
                return false;
            }
        }
        
        //表单验证
        if (strlen($params['zip']) <> '6') {
            $err_msg    = '请输入正确的邮编';
            return false;
        }
        
        //固定电话与手机必填一项
        $gd_tel = str_replace(" ", "", $params['tel']);
        $mobile = str_replace(" ", "", $params['mobile']);
        if (!$gd_tel && !$mobile) {
            $err_msg    = '固定电话与手机号码必需填写一项';
            return false;
        }
        
        $pattern = "/^400\d{7}$/";
        $pattern1 = "/^\d{1,4}-\d{7,8}(-\d{1,6})?$/i";
        if ($gd_tel) {
            $_rs = preg_match($pattern, $gd_tel);
            $_rs1 = preg_match($pattern1, $gd_tel);
            if ((!$_rs) && (!$_rs1)) {
                $err_msg    = '请填写正确的固定电话号码';
                return false;
            }
        }
        
        $pattern2 = "/^\d{8,15}$/i";
        if ($mobile) {
            if (!preg_match($pattern2, $mobile)) {
                $err_msg    = '请输入正确的手机号码';
                return false;
            }
            if ($mobile[0] == '0') {
                $err_msg    = '手机号码前请不要加0';
                return false;
            }
        }
        
        //识别是新增还是编辑
        $params['is_new_add']    = intval($params['org_id']) ? false : true;
        
        if($params['is_new_add']){
            $check_org_no_exist = $organizationObj->dump(array("org_no"=>$params["org_no"]),"org_id");
            if($check_org_no_exist){
                $err_msg    = '新增的编码已经存在';
                return false;
            }
            
            $check_org_name_exist = $organizationObj->dump(array("org_name"=>$params["org_name"]),"org_id");
            if($check_org_name_exist){
                $err_msg    = '新增的名称已经存在';
                return false;
            }
            
        }else{
            $check_org_no_exist = $organizationObj->dump(array("org_no"=>$params["org_no"]),"org_id");
            if($check_org_no_exist && $check_org_no_exist['org_id'] != $params['org_id']){
                $err_msg    = '编辑的编码已经存在';
                return false;
            }
            
            $check_org_name_exist = $organizationObj->dump(array("org_name"=>$params["org_name"]),"org_id");
            if($check_org_name_exist && $check_org_name_exist['org_id'] != $params['org_id']){
                $this->end(false,'编辑的名称已经存在');
            }
            
            //编辑的时候，取一下门店原有的信息
            $old_org_info = $organizationObj->dump(array("org_id"=>$params['org_id']),"org_id,parent_id");
            $params['old_org_info']    = $old_org_info;
        }
        
        return true;
    }

    //根据门店编码找到对应的仓库ID
    public function getBranchIdByStoreBn($store_bn){
        $storeObj = app::get('o2o')->model('store');
        $storeInfo = $storeObj->getList('branch_id',array('store_bn'=>$store_bn), 0, 1);
        if($storeInfo){
            return $storeInfo[0]['branch_id'];
        }
    }
}